// =======================================================================
// 
//       Filename:  textelement.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  20.04.2010 00:53:56
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  Dominik 'domachine' Burgdörfer (-), dominik.burgdoerfer@googlemail.com
//        Company:  -
// 
// =======================================================================

#include "text.hpp"
#include "../utils/citerator.hpp"
#include "../exceptions/fileerror.hpp"
#include <stdexcept>

using namespace std;
using webplodder::exceptions::FileError;
namespace fs = boost::filesystem;

namespace webplodder {
    namespace elements {
        Text::Text(Element& parent, Element::Type type)
            : Element(parent, type),
              mBegin(-1), mEnd(-1),
              mIterator(0)
        {

        }

        Text::Text(Element& parent, 
                    int begin, int end,
                    Element::Type type)
            : Element(parent, TEXT),
              mBegin(begin), mEnd(end),
              mIterator(0)
        {

        }

        Text::~Text() {
        }

        int Text::begin() const
        {
            return mBegin;
        }

        void Text::setBegin(int begin)
        {
            mBegin = begin;
        }

        int Text::end() const
        {
            return mEnd;
        }

        void Text::setEnd(int end)
        {
            mEnd = end;
        }

        void Text::setInput(utils::CIterator& input)
        {
            mIterator = &input;
            while(mIterator->position() < begin())
                mIterator->moveForward();
        }

        void Text::setExternalFile(const fs::path& filePath)
        {
            m_externalFilePath = filePath;
        }

        fs::path Text::externalFile() const
        {
            return m_externalFilePath;
        }

        bool Text::hasExternalFile() const
        {
            return (!m_externalFilePath.empty());
        }

        bool Text::operator>>(char& ch) {
            return getChar(ch);
        }

        bool Text::getChar(char& ch)
        {
            if(!this->hasExternalFile() && begin() < 0)
                return false;

            if(mIterator == 0)
                throw logic_error("No input iterator set");

            if(mIterator->good()) {
                if(mIterator->position() < end() || end() == -1)
                {
                    ch = mIterator->currentChar();
                    mIterator->moveForward();

                    return true;
                }
            }

            mIterator = 0;
            return false;
        }
    }
}

bool operator<<(char& ch, webplodder::elements::Text& element)
{
    return element >> ch;
}

